<template>
  <view class="box">
    <!-- 标题 -->
    <view class="head_title">
      <view>验证码登录</view>
      <view style="margin-left: auto" @tap="usePwdLogin"
        >使用密码登录&nbsp;&gt;</view
      >
    </view>
    <view class="phone_captcha">
      <view class="phone">
        <view>手机号码</view>
        <view>
          <input type="text" placeholder="请输入手机号码" v-model="phone" />
        </view>
      </view>

      <view class="phone captcha">
        <view>验证码</view>
        <view>
          <input type="text" placeholder="请输入验证码" v-model="captcha" />
          <button :disabled="disabled" @tap="getCaptcha">
            {{ msg || msgAndTime }}
          </button>
        </view>
      </view>
    </view>

    <!-- 登录按钮 -->
    <button
      @tap="login"
      :disabled="checkCaptchaAndPhone"
      :class="[checkCaptchaAndPhone ? 'normal' : 'active']"
    >
      登录
    </button>
  </view>
</template>

<script>
import { setToken } from "@/utils/token.js";
import { sendCaptcha, verifyCode, loginUseCaptcha } from "@/api/index.js";
export default {
  name: "captch",
  data() {
    return {
      //获取验证码的定时器
      timer: null,
      phone: "",
      time: 60,
      msg: "获取验证码",
      disabled: false,
      captcha: "",
    };
  },

  methods: {
    usePwdLogin(e) {
      uni.navigateBack({
        delta: 1,
      });
    },
    // 校验手机号
    checkPhoneValid() {
      let regex =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (this.phone == "") {
        uni.showToast({
          title: "请输入手机号",
          duration: 2000,
          icon: "error",
        });
        return;
      } else if (!regex.test(this.phone)) {
        uni.showToast({
          title: "手机号格式错误",
          duration: 2000,
          icon: "error",
        });
        return;
      } else {
        return true;
      }
    },

    // 获取验证码
    async getCaptcha(e) {
      // 发送请求获取验证码,检查手机号格式
      if (this.checkPhoneValid()) {
        // 保证定时器唯一
        if (this.timer) {
          return;
        }
        try {
          let data = await sendCaptcha(this.phone);
          if (data.code == 200) {
            uni.showToast({
              icon: "success",
              title: "验证码发送成功",
            });
          }
          this.msg = "";
          this.disabled = true;
          this.timer = setInterval(() => {
            if (this.time === 1) {
              // 恢复默认的消息
              clearInterval(this.timer);
              this.msg = "获取验证码";
              this.timer = null;
              this.time = 60;
              this.disabled = false;
            }
            this.time -= 1;
          }, 1000);
        } catch (error) {
          uni.showToast({
            title: error.message,
            duration: 2000,
            icon: "error",
          });
        }
      }
    },

    async login() {
      let { phone, captcha } = this;
      // 先校验手机
      // 判断验证码是否有
      if (this.checkPhoneValid()) {
        if (captcha == "") {
          uni.showToast({
            title: "请输入验证码",
            icon: "error",
            duration: 2000,
          });
          return;
        } else {
          try {
            let data = await verifyCode(phone, captcha);
            if (data.code == 200) {
              try {
                let result = await loginUseCaptcha(phone, captcha);
                console.log("这是最终返回的结果", result);
                setToken(result.token);
                //保存用户id用于获取用户id
                uni.setStorageSync("userId", result.profile.userId);
                uni.setStorageSync("cookie", result.cookie);
                if (result.code == 200) {
                  uni.switchTab({
                    url: "/pages/home/index",
                  });
                }
              } catch (error) {
                uni.showToast({
                  title: error.message,
                  icon: "error",
                  duration: 2000,
                });
              }
            }
          } catch (error) {
            uni.showToast({
              title: error.message,
              icon: "error",
              duration: 2000,
            });
          }
        }
      }
    },
  },

  onLoad(params) {
    //获取从主界面传递过来的号码进行展示
    this.phone = params.phone;
  },

  computed: {
    msgAndTime() {
      return "重新发送" + "   " + this.time;
    },
    // 判断验证码和手机号是否填写
    checkCaptchaAndPhone() {
      if (this.captcha == "" || this.phone == "") {
        return true;
      }
      return false;
    },
  },
};
</script>

<style lang="less" scoped>
page {
  width: 100%;
  height: 100%;
}
.box {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  .head_title {
    display: flex;
    width: 90%;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: nowrap;
    margin-top: 100rpx;
    view:nth-child(1) {
      font-size: 48rpx;
      color: #000000;
    }
    view:nth-child(2) {
      font-size: 32rpx;
    }
  }

  .phone_captcha {
    width: 90%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-wrap: wrap;
    margin-top: 100rpx;

    .phone {
      position: relative;
      width: 100%;
      view:nth-child(1) {
        font-size: 40rpx;
      }
      view:nth-child(2) {
        width: 100%;
        height: 80rpx;
        input {
          width: 100%;
          height: 100%;
          color: #000000;
          font-size: 38rpx;
          border-bottom: 1px solid #000000;
        }

        //当鼠标经过输入框
        input:hover {
          border-bottom: 1px solid rgb(63, 133, 255);
        }

        button {
          position: absolute;
          top: 30rpx;
          right: 20rpx;
          width: auto;
        }
      }
    }

    .captcha {
      margin-top: 40rpx;
    }
  }

  & > button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80%;
    margin-top: 80rpx;
    color: #ffffff;
  }
  .normal {
    background-color: rgb(128, 183, 255);
  }

  .active {
    background-color: rgb(98, 98, 219);
  }
}
</style>